'use strict';

var userImpl = require('./dao_impl/user.js');
var threadImpl = require('./dao_impl/thread.js');
var ferror = require('../common/app_utils.js').formatError;
var fout = require('../common/app_utils.js').formatOutput;
var errInfo = require('../common/err_info.js');
var debug = require('debug')('dao_thread');

function MongoDao() {
	var self = this instanceof MongoDao ? this : new MongoDao();
	return self;
}

module.exports = new MongoDao();
var theProto = MongoDao.prototype;

// create a thread
theProto.create = function(json) {
	if (!json.userId) {
		return new Promise(function(fulfil, reject) {
			return fulfil(ferror(errInfo.E2000));
		});
	}

	return userImpl.readById(json.userId)

	.then(function(result) {
		if (result.errCode !== 0) {
			return ferror(errInfo.E2000);
		} else {
			return threadImpl.create(json);
		}
	}, function(err) {
		return err;
	});
};


// read threads
// json page:1,size:10

theProto.read = function(json) {
	var skip = (json.page - 1) * json.size;
	// var now = new Date().getTime();
	// return new Promise(function(f, r) {
	// 	setTimeout(function() {
	// 		f();
	// 	}, 2000);
	// })

	// .then(function() {
	// 	return threadImpl.read({
	// 		query: {},
	// 		skip: skip >= 0 ? skip : 0,
	// 		limit: json.size,
	// 		sort: {
	// 			createdAt: -1
	// 		}
	// 	});
	// });

	// json: {query:q, limit:l, skip:s, projection:p, sort:s}
	return threadImpl.read({
		query: {},
		skip: skip >= 0 ? skip : 0,
		limit: json.size,
		sort: {
			createdAt: -1
		}
	});
};